<?php

class usersController extends manageController {
    /**
     * 发送验证码
     */
    public function creatCodeAction(){
        $phone = (!empty($this->params['phone'])) ? $this->params['phone'] : '';
        $code = Data::getSalt(5);
        $data['mobile'] = $phone;
        $data['content'] = '您的验证码是：'.$code.' 请在5分钟内输入有效';
        $fields['code'] = $code;
        $fields['temp_phone'] = $phone;
        $fields['status'] = 1;
        $fields['createdt'] = 'now()';
        $id = $this->model->addItem($fields,'check_phone');
        if($id){
            $cloundsms=new CloudSMS();
            $cloundsms->sendMessages($phone,$code);
        }
    }

    /**
     * 用户注册
     */
    public function regAction(){
        if($_SERVER['REQUEST_METHOD'] == 'POST'){
            $table = 'users';
            $phone = (!empty($this->params['phone'])) ? $this->params['phone'] : '';                            # 手机号
            $checkCode = (!empty($this->params['checkcode'])) ? $this->params['checkcode'] : '';                # 验证码
            $whereR = array("AND" => array("=" => array('tel'=>$phone, "isdeleted"=>0)));
            $usersInfo = $this->model->getItemByOther($whereR,'users');
//            echo '<pre>';
//            var_dump($this->params);die;
            if($usersInfo){
                $_SESSION['users']['tel'] = $phone;
                echo json_encode(['status'=>1,'msg'=>'登录成功']);
            }else{
                # 判断验证码是否有效
                $sql = "select * from check_phone where temp_phone = '$phone' AND status = 1 order by createdt desc ";
                $res = $this->model->getAny($sql);
                if (!empty($res)) {
                    while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                        $checkPhone[] = $row;
                    }
                }
                if(!$checkPhone){
                    echo json_encode(['status'=>0,'msg'=>'无效手机号']);
                    exit;
                }
                $begin = strtotime($checkPhone[0]['createdt']);
                $end = time();
                $difference = $this->timediff($begin,$end);
                if($difference['min'] >= 5){
                    $columns['temp_phone'] = $phone;
                    $columns['status'] = 0;
                    $whereU = array("AND" => array("=" => array('temp_phone'=>$phone, "status"=>1)));
                    $this->model->updateItem($columns,$whereU,'check_phone');
                    echo json_encode(['status'=>0,'msg'=>'验证码失效']);
                    exit;
                }
                if($checkPhone[0]['code'] == $checkCode){
                    $fields['tel'] = $phone;
                    $fields['status'] = 1;
                    $fields['createdt'] = 'now()';
                    $status = $this->model->addItem($fields,$table);
                    if($status){
                        $columns['temp_phone'] = $phone;
                        $columns['status'] = 0;
                        $whereU = array("AND" => array("=" => array('temp_phone'=>$phone, "status"=>1)));
                        $this->model->updateItem($columns,$whereU,'check_phone');
                        $_SESSION['users']['tel'] = $phone;
                        //日志
                        $logs = array();
                        $logs['table_id'] = $status;
                        $logs['table_name'] = $table;
                        $logs['type'] = "ADD";
                        $logs['page'] = "新增用户";
                        $logs['content'] = $logs['page'] . "：" . 1;
                        $this->model->setLog($logs, array(), $fields);
                        echo json_encode(['status'=>1,'msg'=>'恭喜您注册成功']);
                    }else{
                        echo json_encode(['status'=>0,'msg'=>'系统繁忙']);
                    }
                }else{
                    echo json_encode(['status'=>0,'msg'=>'验证码错误']);
                }
            }
            exit;
        }
        $this->view->setVariable("title", '注册');
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    function timediff($begin_time,$end_time)
    {
        if($begin_time < $end_time){
            $starttime = $begin_time;
            $endtime = $end_time;
        }else{
            $starttime = $end_time;
            $endtime = $begin_time;
        }
        $timediff = $endtime-$starttime;
        $remain = $timediff%86400;
        $remain = $remain%3600;
        $mins = intval($remain/60);
        $secs = $remain%60;
        $res = array("min" => $mins,"sec" => $secs);
        return $res;
    }


    /**
     *  订单列表
     * 2020-1-10 确认查询订单方式  当前的登录手机号  like 数据库 订购人字段“buyer”
     */
    public function ordersListAction() {
        if (!isset($_SESSION['users']['tel'])) {
            Tools::AlertTxt('?md=users&cl=users&at=reg', '请先登录');
            exit;
        }
        $whereR = array("AND" => array("=" => array('tel'=>$_SESSION['users']['tel'], "isdeleted"=>0)));
        $usersInfo = $this->model->getItemByOther($whereR,'users');
        if($usersInfo){
            $sql = "SELECT * FROM orders  WHERE (status >= 0 AND status < 5) AND buyer like'%{$_SESSION['users']['tel']}%' AND isdeleted = 0 ";
            $res = $this->model->getAny($sql);
            if (!empty($res)) {
                while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                    $rsp_list[] = $row;
                }
            }
            if($rsp_list){
                foreach($rsp_list as &$v){
                    $expSql = "SELECT shop_express_no,shop_delivery_address from orders_express where ph_no = '{$v['ph_no']}' and isdeleted = 0";
                    $resE = $this->model->getAny($expSql);

                    if (!empty($resE)) {
                        while ($rowE = mysqli_fetch_array($resE, MYSQLI_ASSOC)) {
                            $v['shop_express_no'] = $rowE['shop_express_no'];
                            $v['receiver_address'] = $rowE['shop_delivery_address'];
                        }

                    }
                }


                $storeSql = "SELECT id,front_province,front_city,front_area,front_address,longitude,latitude,store_id,storename from xd_store where (status = 2 or status = 4 or status = 5)  and isdeleted = 0";
                $res = $this->model->getAny($storeSql);
                if (!empty($res)) {
                    while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                        $shopsList[] = $row;
                    }
                }

                foreach ($rsp_list as $k=>&$p){
                    foreach ($shopsList as $s){
                        if($p['shop_no'] == $s['store_id']){
                            $p['shop'] = $s;
                        }
                    }
                }
            }
        }
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("title", '订单列表');
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    /**
     *  订单详情
     */
    public function orderDetailsAction() {
        if (!isset($_SESSION['users']['tel'])) {
            Tools::AlertTxt('?md=users&cl=users&at=reg', '请先登录');
            exit;
        }
        $orders_id = (!empty($this->params['orders_id'])) ? (int) $this->params['orders_id'] : '';
        $type = (!empty($this->params['type'])) ? (int) $this->params['type'] : '';
        # 订单
        $whereOrder = ['AND'=>['='=>['id'=>$orders_id, "isdeleted"=>0]]];
        $orderInfo = $this->model->getItemByOther($whereOrder,'orders');

        # 派单详情
        $whereOrderE = array("AND" => array("=" => array('ph_no'=>$orderInfo[0]['ph_no'], "isdeleted"=>0)));
        if($type == 'finish'){
            $whereOrderE ['AND']['=']['status']= 5;
        }else{
            $whereOrderE ['AND']['<']['status']= 5;
        }
        $ExpressInfo = $this->model->getItemByOther($whereOrderE,'orders_express');
        # 商品详情
        $whereOrderProduct = ['AND'=>['='=>['ph_no'=>$orderInfo[0]['ph_no']]]];
        $orderProductInfo = $this->model->getItemByOther($whereOrderProduct,'orders_product');

        # 门店详情
        $whereShop = ['AND'=>['='=>['store_id'=>$orderInfo[0]['shop_no']]]];
        $shopInfo = $this->model->getItemByOther($whereShop,'xd_store');


        # 筛选 门店修改地址
        $where = array('AND' => array('=' => array('orders_id' => $orderInfo[0]['id'], 'status' => 1, "isdeleted" => 0)));
        $orderby = ['createdt' => 'desc'];
        $shop_delivery_address = $this->model->getAll($where, 'shop_delivery_address', $orderby);
        if($shop_delivery_address && is_array($shop_delivery_address) && count($shop_delivery_address) > 0){
            $orderInfo[0]['receiver'] = $shop_delivery_address[0]['receiver_name'];
            $orderInfo[0]['receiver_tel'] = $shop_delivery_address[0]['receiver_tel'];
            $orderInfo[0]['receiver_address'] = $shop_delivery_address[0]['receiver_address'];
        }

        $orderExpressInfo['orderInfo'] = $orderInfo[0];
        $orderExpressInfo['orderProductInfo'] = $orderProductInfo;
        $orderExpressInfo['shopInfo'] = $shopInfo[0];
        $orderExpressInfo['express'] = $ExpressInfo[0];
        $this->view->setVariable("orderExpressInfo", $orderExpressInfo);
        $this->view->setVariable("title", '订单详情');
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }


    /**
     * 求两个已知经纬度之间的距离,单位为米
     * @param lng1 $ ,lng2 经度
     * @param lat1 $ ,lat2 纬度
     * @return float 距离，单位米
     */
    function getdistanceAction($lng1, $lat1, $lng2, $lat2) {
        $radLat1 = deg2rad($lat1);
        $radLat2 = deg2rad($lat2);
        $radLng1 = deg2rad($lng1);
        $radLng2 = deg2rad($lng2);
        $a = $radLat1 - $radLat2;
        $b = $radLng1 - $radLng2;
        $s = 2 * asin(sqrt(pow(sin($a / 2), 2) + cos($radLat1) * cos($radLat2) * pow(sin($b / 2), 2))) * 6378.137 * 1000;
        return $s;
    }



    /**
     *  订单完成列表
     * 2020-1-10 确认查询订单方式  当前的登录手机号  like 数据库 订购人字段“buyer”
     */
    public function ordersFinishAction() {
        if (!isset($_SESSION['users']['tel'])) {
            Tools::AlertTxt('?md=users&cl=users&at=reg', '请先登录');
            exit;
        }
        $table = "orders";
        $whereR = array("AND" => array("=" => array('tel'=>$_SESSION['users']['tel'], "isdeleted"=>0)));
        $usersInfo = $this->model->getItemByOther($whereR,'users');
        if($usersInfo){
            $sql = "SELECT * FROM $table  WHERE status = 5 AND buyer like'%{$_SESSION['users']['tel']}%' AND isdeleted = 0 ";
            $res_o = $this->model->getAny($sql);
            $rsp_list = '';
            if (!empty($res_o)) {
                while ($row_o = mysqli_fetch_array($res_o, MYSQLI_ASSOC)) {
                    $rsp_list[] = $row_o;
                }
            }
            $storeSql = "SELECT id,front_province,front_city,front_area,front_address,longitude,latitude,store_id,storename from xd_store where (status = 2 or status = 4 or status = 5)  and isdeleted = 0";
            $res = $this->model->getAny($storeSql);
            if (!empty($res)) {
                while ($row = mysqli_fetch_array($res, MYSQLI_ASSOC)) {
                    $shopsList[] = $row;
                }
            }

            if($rsp_list){
                foreach($rsp_list as &$v){
                    $expSql = "SELECT shop_express_no from orders_express where ph_no = '{$v['ph_no']}' and isdeleted = 0";
                    $resE = $this->model->getAny($expSql);
                    if (!empty($resE)) {
                        while ($rowE = mysqli_fetch_array($resE, MYSQLI_ASSOC)) {
                            $v['shop_express_no'] = $rowE[0]['shop_express_no'];
                        }
                    }
                }

                foreach ($rsp_list as $k=>&$p){
                    foreach ($shopsList as $s){
                        if($p['shop_no'] == $s['store_id']){
                            $p['shop'] = $s;
                        }
                    }
                }
            }

        }
        $this->view->setVariable("rsp_list", $rsp_list);
        $this->view->setVariable("title", '订单列表');
        $this->view->setViewfilepath(MvcReg::$_moduleName . '/views/' . MvcReg::$_actionName . 'View.php');
        $this->view->render();
    }
}
